package com.example.hasee.gridviewtest;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class GridViewActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gridview);
        setTitle("网络视图");
        GridView gv = (GridView) findViewById(R.id.grid_view);
        gv.setAdapter(new ImageAdapter(this));
    }

    public class  ImageAdapter extends BaseAdapter{
        //定义Context
        private Context mContext;

        public ImageAdapter(Context c){
            mContext = c;
        }

        //图片的引用 定义整型数据 即图片源
        private Integer[] mThumbIds = {
                R.drawable.apple,R.drawable.banana,
                R.drawable.grape,R.drawable.mango,
                R.drawable.orange,R.drawable.pear,
                R.drawable.watermelon
        };

        //获取图片个数
        public int getCount(){
            return mThumbIds.length;
        }

        //获取图片在库中的位置
        public Object getItem(int arg0){
            // TODO Auto-generated method stub
            return  null;
        }

        //获取图片ID
        @Override
        public long getItemId(int arg0){
            //TODO Auto-generated method stub

            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent){
            ImageView imageView;
            if (convertView == null){//if it's not recycled, initialize some
                //attributes
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(2, 2, 2, 2);

            }else{
                imageView = (ImageView) convertView;
            }

            imageView.setImageResource(mThumbIds[position]);
            return imageView;
        }
    }
}
